#!/bin/bash
plugin=dynamix.cache.dirs
script=cache_dirs
execute=/usr/local/emhttp/plugins/$plugin/scripts/$script
options=/etc/$script.conf
run=/tmp/$script.run

cache_dirs.start() {
  if [[ -z $(pgrep -f $execute) ]]; then
    # ensure folder names are properly quoted
    echo "$execute $(cat $options) 2>/dev/null" >$run
    source $run
    rm -f $run
    echo "$script started"
    echo "cache_dirs service $(basename "$0"): Started: '$execute $(cat $options) 2>/dev/null'" | logger "-tcache_dirs"
  else
    echo "$script already running!"
  fi
}

cache_dirs.stop() {
  if [[ -n $(pgrep -f $execute) ]]; then
    $execute -q &>/dev/null
    timer=5
    until [[ -z $(pgrep -f $execute) || $timer -eq 0 ]]; do
      timer=$((timer-1))
      sleep 1
    done
    if  [[ -z $(pgrep -f $execute) ]]; then
      echo "cache_dirs service $(basename "$0"): Stopped" | logger "-tcache_dirs"
    else
      echo "$script process still running" | logger "-tcache_dirs"
    fi
  else
    # Always execute because cache_dirs uses subprocesses and lock-file, and it may need to cleanup
    $execute -q &>/dev/null
    echo "$script not running!"
  fi
}

cache_dirs.restart() {
  cache_dirs.stop
  sleep 1
  cache_dirs.start
}

case "$1" in
'start')
 cache_dirs.start ;;
'stop')
 cache_dirs.stop ;;
'restart')
 cache_dirs.restart ;;
*)
 echo "Usage: $(basename $0) start|stop|restart"
esac
